package com.sale.system.controller;

import com.sale.common.core.domain.R;
import com.sale.common.core.web.controller.BaseController;
import com.sale.common.log.annotation.Log;
import com.sale.common.log.enums.BusinessType;
import com.sale.common.mybatis.core.page.PageQuery;
import com.sale.common.mybatis.core.page.TableDataInfo;
import com.sale.system.domain.SysCustomerManagement;
import com.sale.system.domain.dto.SysCustomerManagementDto;
import com.sale.system.domain.vo.SysCustomerManagementVo;
import com.sale.system.domain.vo.OrderReviewVo;
import com.sale.system.export.CustomerManagementExport;
import com.sale.system.export.CustomerManagementimportExport;
import com.sale.system.service.SysCustomerManagementService;
import com.sale.system.util.ExcelUtil;
import lombok.RequiredArgsConstructor;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * 客户管理控制层
 */
@RequiredArgsConstructor
@RestController
@RequestMapping("/customer-management")
public class SysCustomerManagementController extends BaseController {

    private final SysCustomerManagementService sysCustomerManagementService;

    /**
     * 客户管理列表
     */
    //@SaCheckPermission("order:customer:list")
    @GetMapping("/list")
    public TableDataInfo<SysCustomerManagementDto> list(SysCustomerManagementVo sysCustomerManagementVo, PageQuery pageQuery) {
        //查询加工商列表
        return sysCustomerManagementService.getList(sysCustomerManagementVo,pageQuery);
    }


    /**
     * 新增客户
     */
    //@SaCheckPermission("order:sale:customer:add")
    @Log(title = "新增客户", businessType = BusinessType.INSERT)
    @PostMapping("/add")
    public R<Void> add(@Validated @RequestBody SysCustomerManagementVo sysCustomerManagementVo) throws Exception {
        return toAjax(sysCustomerManagementService.addConverter(sysCustomerManagementVo));
    }

    /**
     * 客户修改
     */
    //@SaCheckPermission("order:sale:customer:edit")
    @Log(title = "客户修改", businessType = BusinessType.UPDATE)
    @PutMapping("/update")
    public R<Void> update(@Validated @RequestBody SysCustomerManagementVo sysCustomerManagementVo) throws Exception {
        return toAjax(sysCustomerManagementService.updateCustomerById(sysCustomerManagementVo));
    }

    /**
     * 删除客户
     */
    //@SaCheckPermission("order:sale:customer:remove")
    @Log(title = "删除客户", businessType = BusinessType.DELETE)
    @DeleteMapping("/delete/{ids}")
    public R<Void> view(@PathVariable("ids") String ids) throws Exception {
        return toAjax(sysCustomerManagementService.getDeleteByIds(ids));
    }

    /**
     * 查看客户信息
     */
    //@SaCheckPermission("order:sale:customer:query")
    @GetMapping("/view/{id}")
    public R<SysCustomerManagementDto> customerView(@PathVariable("id") Long id) {
        return R.ok(sysCustomerManagementService.getCustomerById(id));
    }

    /**
     * 修改客户启用状态
     */
    //@SaCheckPermission("order:sale:customer:updateStatus")
    @PutMapping("/updateStatus")
    public R<Void> updateStatus(@RequestBody SysCustomerManagementVo sysCustomerManagementVo) {
        return toAjax(sysCustomerManagementService.updateStatus(sysCustomerManagementVo));
    }

    /**
     * 获取启用的客户列表
     */
    @GetMapping("/getOpenCustomer")
    public R<List<HashMap<String,String>>> getOpenCustomer() {
        List<HashMap<String,String>> resultMap = new ArrayList<>();
        List<SysCustomerManagementDto> openCustomer = sysCustomerManagementService.getOpenCustomer();
        for(SysCustomerManagementDto entity : openCustomer){
            HashMap<String, String> map = new HashMap<>();
            map.put("label",entity.getCustomerName());
            map.put("value",entity.getCustomerNum());
            resultMap.add(map);
        }
        return R.ok(resultMap);
    }

    /**
     * 获取启用的客户列表（财务模块调用）
     */
    @GetMapping("/getOpenCustomerFinance")
    public R<Map<String,String>> getOpenCustomerFinance() {
        List<SysCustomerManagementDto> openCustomer = sysCustomerManagementService.getOpenCustomer();
        Map<String, String> collect = openCustomer.stream()
            .collect(Collectors.toMap(SysCustomerManagementDto::getCustomerNum, SysCustomerManagementDto::getCustomerName));
        return R.ok(collect);
    }

    /**
     * 冻结客户
     */
    //@SaCheckPermission("order:sale:customer:frozen")
    @Log(title = "冻结客户", businessType = BusinessType.UPDATE)
    @GetMapping("/frozen/{id}")
    public R<Void> frozenSupplier(@PathVariable("id") Long id) {
        return toAjax(sysCustomerManagementService.frozenSupplier(id));
    }

    /**
     * 解冻客户
     */
    //@SaCheckPermission("order:sale:customer:thaw")
    @Log(title = "解冻客户", businessType = BusinessType.UPDATE)
    @GetMapping("/thaw/{id}")
    public R<Void> thawSupplier(@PathVariable("id") Long id) {
        return toAjax(sysCustomerManagementService.thawSupplier(id));
    }

    /**
     * 撤销审核
     */
    //@SaCheckPermission("order:sale:customer:revoke")
    @Log(title = "撤销审核", businessType = BusinessType.UPDATE)
    @GetMapping("/revoke/{id}")
    public R<Void> revokeApproval(@PathVariable("id") Long id) {
        return toAjax(sysCustomerManagementService.revokeApproval(id));
    }


//    /**
//     * 生成客户导入模板
//     */
//    @PostMapping("/customerTemplate")
//    public AjaxResult supplierTemplate(HttpServletResponse response) throws IOException {
//        ExcelUtil<CustomerManagementimportExport> excelUtil = new ExcelUtil<CustomerManagementimportExport>(CustomerManagementimportExport.class);
//        excelUtil.exportTemplate(response, null, "客户信息.xlsx");
//        return AjaxResult.success();
//    }

    /**
     * 生成客户导入模板
     */
    @PostMapping("/downTemplate")
    public void downTemplate(HttpServletResponse response) throws IOException {
        String fileName = "C:/Users/jack/Desktop/导入导出模板/导入模板/导入客户.xlsx";
        File file = new File(fileName);
        ByteArrayOutputStream baos = null;
        ServletOutputStream out = null;
        try {

            InputStream inStream=new FileInputStream(file);
            byte[] buffer = new byte[1024];
            int len;
            baos = new ByteArrayOutputStream();
            while ((len = inStream.read(buffer)) != -1) {
                baos.write(buffer, 0, len);
            }
            response.setContentType("application/octet-stream;charset=UTF-8");
            response.setHeader("Content-Disposition","attachment;filename=" + URLEncoder.encode("导入客户.xlsx","UTF-8"));
            out = response.getOutputStream();
            out.write(baos.toByteArray());
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            baos.flush();
            baos.close();
            out.flush();
            out.close();
        }
    }

    /**
     * 客户信息导出
     */
    //@SaCheckPermission("order:sale:customer:export")
    @PostMapping("/customerMessageExport")
    public R mouldMessageExport(HttpServletResponse response, SysCustomerManagementVo sysCustomerManagementVo) throws IOException {
        List<CustomerManagementExport> infoExport = sysCustomerManagementService.getInfoExport(sysCustomerManagementVo);
        ExcelUtil<CustomerManagementExport> excelUtil = new ExcelUtil<CustomerManagementExport>(CustomerManagementExport.class);
        excelUtil.excelWriter(response, infoExport, "客户信息.xlsx");
        return R.ok();
    }

    /**
     * 客户信息导入
     */
    //@SaCheckPermission("order:sale:customer:import")
    @Log(title = "客户信息导入", businessType = BusinessType.INSERT)
    @PostMapping("/customerMessageImport")
    public R mouldMessageImport(MultipartFile file) throws IOException {
        ExcelUtil<CustomerManagementimportExport> excelUtil = new ExcelUtil<CustomerManagementimportExport>(CustomerManagementimportExport.class);
        List<CustomerManagementimportExport> coCustomer = excelUtil.importExcel(file.getInputStream());
        return R.ok(sysCustomerManagementService.importMouldData(coCustomer));
    }

    /**
     * 提交审核
     */
    //@SaCheckPermission("order:sale:customer:subExamine")
    @Log(title = "提交审核", businessType = BusinessType.UPDATE)
    @GetMapping("/reviewSubmit/{id}")
    public R<Void> reivewSubmit(@PathVariable("id") Long id) {
        return toAjax(sysCustomerManagementService.reivewSubmit(id));
    }

    /**
     * 客户审核
     */
    //@SaCheckPermission("order:sale:customer:review")
    @Log(title = "供应商审核", businessType = BusinessType.UPDATE)
    @PostMapping("/customerReview")
    public R<Void> customerReview(@Validated @RequestBody OrderReviewVo orderReviewVo) throws Exception {
        return toAjax(sysCustomerManagementService.customerReview(orderReviewVo));
    }

    /**
     * Feign通过客户名称查出客户id
     */
    @GetMapping("/getCustomerId")
    public SysCustomerManagement getCustomerId(String customerName) {
        return sysCustomerManagementService.getCustomerId(customerName);
    }

    /**
     * 通过客户编码获取客户信息
     */
/*    @GetMapping("/getCustomerByCode/{customerCode}")
    public R<CustomerManagementResultDto> getCustomerByCode(@PathVariable("customerCode") String customerCode) {
        return R.ok(customerManagementService.getCustomerByCode(customerCode));
    }*/

    /**
     * 通过客户名称获取客户编码(财务模块使用)
     */
/*    @GetMapping("/getCodeByCustomerName")
    public String getCodeByCustomerName(String customerName) {
        return customerManagementService.getCodeByCustomerName(customerName);
    }*/


}
